package com.itopener.canal.es.ext.handler;

import java.sql.Types;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
import com.alibaba.otter.canal.protocol.CanalEntry.RowData;
import com.itopener.canal.es.core.handler.AbstractEventHandler;
import com.itopener.canal.es.ext.model.ModelExample;
import com.itopener.canal.es.ext.repos.RepositoryExample;

@Component
public class EventHandlerExample extends AbstractEventHandler {
	
//	private final Logger logger = LoggerFactory.getLogger(EventHandlerExample.class);
	
	@Resource
	private RepositoryExample repositoryExample;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public String getDatabase() {
		return "canal_demo";
	}

	@Override
	public String getTableName() {
		return "canal_model";
	}

	@Override
	public void handle(Entry entry, RowData rowData) {
		EventType eventType = entry.getHeader().getEventType();
		switch (eventType) {
	        case INSERT:
	        case UPDATE:
	        	// 获取需要作为查询条件的列的值
	        	String id = getAfterColumnValue(rowData, "id");
	        	// 执行查询获取返回结果
	        	String sql = "select id,name,create_time,`date`, concat(x(`point`),',',y(`point`)) as point from canal_model where id = ?";
	        	List<ModelExample> list = jdbcTemplate.query(sql, new String[] {id}, new int[] {Types.BIGINT}, new BeanPropertyRowMapper<>(ModelExample.class));
	        	// 将数据保存到es中
	        	repositoryExample.saveAll(list);
	        	break;
	        case DELETE:
	        	// 从es中删除数据
	        	id = getBeforeColumnValue(rowData, "id");
	        	repositoryExample.deleteById(Long.valueOf(id));
	            break;
	        default:
	            break;
	    }
	}
	
}
